<?php

namespace app\admin\controller;

use app\admin\model\Goods;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

//use think\facade\View;

class Good extends BaseController
{
    public function goodRecovery()
    {
        $keywords = input('get.keywords');
        $show     = input('get.is_show');
        $hot      = input('get.is_hot');
        $down     = input('get.is_down');
        $cid      = input('get.cid');
        $get      = Request::get();
        $where    = [];
        //$arr=[];
        if (isset($keywords) && !empty($keywords)) $where['keywords']       = $keywords;     //= ['g.name', 'like', "%{$keywords}%"];     //$arr['keywords']=$keywords;}
        if (isset($show) && $show != 2 && $show != "") $where['show']       = $show;          //= ['g.is_show', '=', "{$show}"];           //$arr['is_show']=$show;
        if (isset($hot) && $hot != "") $where['hot']                        = $hot;           //= ['g.is_hot', '=', "{$hot}"];             //$arr['is_hot']=$hot;}
        if (isset($down) && $down != "" && !isset($down[1])) $where['down'] = $down;          //= ['g.is_down', '=', "{$down[0]}"];        //$arr['is_down']=$down[0];
        if (isset($cid) && !empty($cid)) $where['cid']                      = $cid;           //= ['g.cid', '=', "{$cid}"];                //$arr['cid']=$cid;
        if (isset($get['timeq']) && $get['timeq'] != "") $where['timeq']    = $get['timeq'];  //= ['g.addtime', '< TIME', $get['timeq']];
        if (isset($get['timeh']) && $get['timeh'] != "") $where['timeh']    = $get['timeh'];  //= ['g.addtime', '> TIME', $get['timeh']];
        if (isset($get['prq']) && $get['prq'] != "") $where['prq']          = $get['prq'];    //= ['g.price_shop', '>', $get['prq']];
        if (isset($get['prh']) && $get['prh'] != "") $where['prh']          = $get['prh'];    //= ['g.price_shop', '<', $get['prh']];
        $where['delete_time'] = null;
        $list = \app\admin\model\Goods::getGoodRecoveryList($where, $get, $keywords);

        $page = $list->toarray()['last_page'];
        if (isset($get['page']) && $get['page'] > $page) {
            $get['page'] = $page;
            return redirect((string) url('admin/Good/goodList', $get));
        }
        if (Cache::has('cate')) { //判断缓存是否存在
            $cateAll = Cache::get('cate'); // 获取缓存数据
        } else {
            $cateAll = \app\admin\model\Category::getCategoryList();
            Cache::set('cate', $cateAll, 100); // 设置缓存变量
        }

        $cate = $this->getCate($cateAll, 0);

        View::assign($get);
        View::assign('list', $list);
        View::assign('cate', $cate);
        return view();
    }
    public function delGood()
    {
        $id = input('get.id');
        $del = input('get.del');
        if ($del == "false") {
            $delgood = Goods::destroy($id);
            if ($delgood) {
                $this->success('删除成功', url('Good/goodList'));
            } else {
                $this->error('网络波动请稍后再试');
            }
        } elseif ($del == "true") {
            $delgood = Goods::destroy($id, true);
            if ($delgood) {
                $this->success('成功删除数据库', url('Good/goodList'));
            } else {
                $this->error('网络波动请稍后再试');
            }
        } elseif ($del == "recovery") {
            $recovery = Goods::onlyTrashed()->find($id)->restore();
            if ($recovery) {
                $this->success('恢复成功', url('Good/goodList'));
            } else {
                $this->error('网络波动请稍后再试');
            }
        }
    }
    public function cateedit()
    {
        $where['parentid'] = "0";
        $cate = \app\admin\model\Category::getWhereList($where);
        $list = \app\admin\model\Category::find(input('get.id'));
        view::assign('list', $list);
        View::assign('cate', $cate);
        if (Request::isPost()) {
            $post = Request::post();
            $post['id'] = input('get.id');
            list($res, $msg) = \app\admin\model\Category::editCate($post);
            if ($res) {
                $this->success($msg, url('admin/Good/cate'));
            } else {
                $this->error($msg);
            }
        }
        return View::fetch();
    }
    public function cate()
    {
        $where['parentid'] = "0";
        $id = input('get.id');
        if (isset($id) && !empty($id)) $where['parentid'] = $id;
        $cate = \app\admin\model\Category::getWhereList($where);
        // $cate = Db::name('category')
        //     ->where($where)
        //     ->order("sort")
        //     ->select()
        //     ->toArray();
        foreach ($cate as $k => $v) {
            $where['parentid'] = $v['id'];
            $son = \app\admin\model\Category::getWhereList($where);
            // $son = Db::name("category")
            //     ->field("id")
            //     ->where("parentid={$v['id']}")
            //     ->order("id")
            //     ->select()
            //     ->toArray();
            if ($son) {
                $cate[$k]['son'] = 1;
            } else {
                $cate[$k]['son'] = 2;
            }
        }
        View::assign('cate', $cate);
        if (Request::isPost()) {
            $post       = Request::post();
            $post['addtime']  = time();
            list($res, $msg) = \app\admin\model\Category::addCate($post);
            if ($res) {
                $this->success($msg, url('admin/Good/cate'));
            } else {
                $this->error($msg);
            }
        } else {
            return view();
        }
        return view();
    }
    public function goodAdd()
    {
        // 判断是添加还是修改
        if (input('?get.id')) {
            $list = \app\admin\model\Goods::find(input('get.id'));
            $arr = explode(",", $list['photo_string']);
            $arr = array_filter($arr);
            //传结果 循环图片和数据
            view::assign('pstring', $arr);
            view::assign('list', $list);
        }
        //判断文件是否上传
        if (Request::isPost()) {
            $post = Request::post();
            //在文件是--添加--的情况下
            //给默认值
            if (!input('?post.is_show')) $post['is_show'] = "0";
            if (!input('?post.is_hot')) $post['is_show']  = "0";
            if (!input('?post.is_down')) $post['is_show'] = "0";
            $post['updatetime'] = time();
            //在文件是--修改--的情况下
            if (!input('?get.id')) {
                // 上传图片并且返回值
                //[真/假,图片地址/错误信息]
                $errorImg = $this->uploadImg('img');
                if ($errorImg[0]) {
                    $post['photo_x'] = $errorImg[1];
                } else {
                    $this->error($errorImg[1]);
                }
                $errorBan = $this->uploadImg('banner');
                if ($errorBan[0]) {
                    $post['photo_string'] = $errorBan[1];
                } else {
                    $this->error($errorBan[1]);
                }
                $post['addtime']  = $post['updatetime'];
                list($res, $msg) = \app\admin\model\Goods::addGoods($post);
            } else {
                $error = $this->uploadImg('img');
                if ($error[0]) {
                    $post['photo_x'] = $error[1];
                } else {
                    if (!$error[1] == "没上传图" && !$error[1] == "no file to uploaded") {
                        $this->error($error[1]);
                    }
                }
                if (!isset($post['photo_string']) || $post['photo_string'] == "" || $post['photo_string'] == null) { //$post['photo_string'] == "" && $post['photo_string'] == null) {
                    unset($post['photo_string']);
                } else {
                    $post['photo_string'] = array_filter($post['photo_string']);
                    $post['photo_string'] = implode(",", $post['photo_string']);
                }
                $post['id'] = input('get.id');
                list($res, $msg) = \app\admin\model\Goods::editGoods($post);
            }
            if ($res) {
                $get = input('get.');
                if (!input('?get.id')) {
                    if (isset($post['photo_x'])) {
                        $rempath = str_replace('\\', '/', app()->getRootPath());
                        $reto = $rempath . "public/static/admin/" . $post['photo_x'];
                        $rempath = $rempath . "public/static/admin/linshi/" . $post['photo_x'];
                        $qianpath = pathinfo($reto)['dirname'] . "/";
                        if (!is_dir($qianpath)) {
                            mkdir($qianpath, 0777, true);
                        }
                        rename($rempath, $reto);
                    }
                    if (isset($post['photo_string'])) {
                        $postarr = explode(",", $post['photo_string']);
                        if (count($postarr) > 0) {
                            foreach ($postarr as $k => $v) {
                                $rempath = str_replace('\\', '/', app()->getRootPath());
                                $reto = $rempath . "public/static/admin/" . $v;
                                $rempath = $rempath . "public/static/admin/linshi/" . $v;
                                $qianpath = pathinfo($reto)['dirname'] . "/";
                                if (!is_dir($qianpath)) {
                                    mkdir($qianpath, 0777, true);
                                }
                                rename($rempath, $reto);
                            }
                        }
                    }
                } else {
                    if (isset($post['photo_x'])  && $error[1] <> "no file to uploaded") {
                        $rempath = str_replace('\\', '/', app()->getRootPath());
                        $reto = $rempath . "public/static/admin/" . $post['photo_x'];
                        $rempath = $rempath . "public/static/admin/linshi/" . $post['photo_x'];
                        $qianpath = pathinfo($reto)['dirname'] . "/";
                        if (!is_dir($qianpath)) {
                            mkdir($qianpath, 0777, true);
                        }
                        rename($rempath, $reto);
                    }
                    if (isset($post['photo_string'])) {
                        $arr = explode(",", $list['photo_string']);
                        $arr = array_filter($arr);
                        $postarr = explode(",", $post['photo_string']);
                        $dif = array_diff($arr, $postarr);
                        if (count($dif) > 0) {
                            foreach ($dif as $k => $v) {
                                $unpath = str_replace('\\', '/', app()->getRootPath());
                                $unpath = $unpath . "public/static/admin/" . $v;
                                if (file_exists($unpath)) {
                                    chmod($unpath, 0777);
                                    unlink($unpath);
                                }
                            }
                        }
                        $ndif = array_diff($postarr, $arr);
                        if (count(array_filter($ndif)) > 0) {
                            foreach ($ndif as $k => $v) {
                                $rempath = str_replace('\\', '/', app()->getRootPath());
                                $reto = $rempath . "public/static/admin/" . $v;
                                $rempath = $rempath . "public/static/admin/linshi/" . $v;
                                $qianpath = pathinfo($reto)['dirname'] . "/";
                                if (!is_dir($qianpath)) {
                                    mkdir($qianpath, 0777, true);
                                }
                                rename($rempath, $reto);
                            }
                        }
                    }
                }
                if (input('post.cz') == 1) {
                    $this->success($msg, url('admin/Good/goodList', $get));
                } else {
                    $this->success($msg, url('admin/Good/goodAdd', $get));
                }
            } else {
                $this->error($msg);
            }
        };
        if (Cache::has('cate')) { //判断缓存是否存在
            $cateAll = Cache::get('cate'); // 获取缓存数据
        } else {
            $cateAll = \app\admin\model\Category::getCategoryList();
            // $cateAll = Db::name('category')->select()->toArray();
            Cache::set('cate', $cateAll, 100); // 设置缓存变量
        }
        $cate = $this->getCate($cateAll, 0);
        view::assign('cate', $cate);
        return view();
    }
    public function goodList()
    {
        $keywords = input('get.keywords');
        $show     = input('get.is_show');
        $hot      = input('get.is_hot');
        $down     = input('get.is_down');
        $cid      = input('get.cid');
        $get      = Request::get();
        $where    = [];
        //$arr=[];
        if (isset($keywords) && !empty($keywords)) $where['keywords']       = $keywords;     //= ['g.name', 'like', "%{$keywords}%"];     //$arr['keywords']=$keywords;}
        if (isset($show) && $show != 2 && $show != "") $where['show']       = $show;          //= ['g.is_show', '=', "{$show}"];           //$arr['is_show']=$show;
        if (isset($hot) && $hot != "") $where['hot']                        = $hot;           //= ['g.is_hot', '=', "{$hot}"];             //$arr['is_hot']=$hot;}
        if (isset($down) && $down != "" && !isset($down[1])) $where['down'] = $down;          //= ['g.is_down', '=', "{$down[0]}"];        //$arr['is_down']=$down[0];
        if (isset($cid) && !empty($cid)) $where['cid']                      = $cid;           //= ['g.cid', '=', "{$cid}"];                //$arr['cid']=$cid;
        if (isset($get['timeq']) && $get['timeq'] != "") $where['timeq']    = $get['timeq'];  //= ['g.addtime', '< TIME', $get['timeq']];
        if (isset($get['timeh']) && $get['timeh'] != "") $where['timeh']    = $get['timeh'];  //= ['g.addtime', '> TIME', $get['timeh']];
        if (isset($get['prq']) && $get['prq'] != "") $where['prq']          = $get['prq'];    //= ['g.price_shop', '>', $get['prq']];
        if (isset($get['prh']) && $get['prh'] != "") $where['prh']          = $get['prh'];    //= ['g.price_shop', '<', $get['prh']];
        // if (isset($get['cid']) && $get['cid'] != "") $where['cid']          = $get['cid'];    //= ['g.cid', '=', $get['cid']];


        $list = \app\admin\model\Goods::getGoodsList($where, $get, $keywords);

        $page = $list->toarray()['last_page'];
        if (isset($get['page']) && $get['page'] > $page) {
            $get['page'] = $page;
            //$this->success("数据处理中请稍等", url('admin/Good/goodList', $get), "", 0);
            return redirect((string) url('admin/Good/goodList', $get));
        }
        // $list = \app\admin\model\Goods::field('g.*,c.name cname')
        //     ->where($where)
        //     ->alias('g')
        //     ->join('category c', 'g.cid=c.id')->paginate([
        //         'list_rows' => 5,
        //         'query' => $get,
        //     ])->each(function ($item, $k) use ($keywords) {
        //         $str = '<span style="color:red;">' . $keywords . '</span>';
        //         $item["name"] = str_replace($keywords, $str, $item['name']);
        //         return $item;
        //     });
        // $list = Db::name('goods')
        //     ->field('g.*,c.name cname')
        //     ->where($where)
        //     ->alias('g')
        //     ->join('category c', 'g.cid=c.id')
        //     //->select()
        //     //->toArray();
        //     ->paginate([
        //         'list_rows' => 5,
        //         'var_page' => 'page',
        //         'query' => $get,
        //     ])->each(function ($item, $k) use ($keywords) {
        //         $str = '<span style="color:red;">' . $keywords . '</span>';
        //         $item["name"] = str_replace($keywords, $str, $item['name']);
        //         return $item;
        //     });
        //if ($keywords!=""){
        //    foreach ($list as $k=>$v){
        //        $str='<span style="color:red;">'.$keywords.'</span>';
        //        $list[$k]["name"]=str_replace($keywords,$str,$v['name']);
        //    }
        //}

        //方案一
        //$cate=Db::name('category')
        //    ->field("id,name")
        //    ->where("parentid=0")
        //    ->order("id")
        //    ->select()
        //    ->toArray();
        //foreach ($cate as $k=>$v){
        //    $son=Db::name("category")
        //        ->field("id,name")
        //        ->where("parentid={$v['id']}")
        //        ->order("id")
        //        ->select();
        //    $cate[$k]['son']=$son;
        //}

        //方案二
        //使用缓存
        if (Cache::has('cate')) { //判断缓存是否存在
            $cateAll = Cache::get('cate'); // 获取缓存数据
        } else {
            $cateAll = \app\admin\model\Category::getCategoryList();
            // $cateAll = Db::name('category')->select()->toArray();
            Cache::set('cate', $cateAll, 100); // 设置缓存变量
        }
        //$cate=[];
        ////循环所有分类
        //foreach ($cateAll as $k=>$v){
        //    //判断 分类中parentid字段等于0 进入判断结果 都是一级分类
        //   if($v['parentid']==0){
        //        //将一级分类赋值到空数组中 索引为自己的ID
        //       $cate[$v['id']]=$v;
        //        //循环所有分类
        //       foreach ($cateAll as $kk=>$vv){
        //            //如果分类的parentid等于上一级分类(一级分类)ID进入判断里的是二级分类
        //           if ($vv['parentid']==$v['id']) {
        //                //将二级分类赋值到数组 根据索引 ($v.id) 将一级和二级绑定到一起
        //               $cate[$v['id']]['son'][]=$vv;
        //           }
        //       }
        //   }
        //}

        //2.2
        $cate = $this->getCate($cateAll, 0);

        View::assign($get);
        View::assign('list', $list);
        View::assign('cate', $cate);
        //input('post.name')
        return view();
    }
    public function getCate($cateAll, $parentid)
    {
        $cate = [];
        foreach ($cateAll as $v) {
            if ($v['parentid'] == $parentid) {
                $cate[$v['id']] = $v;
                $cate[$v['id']]['son'] = $this->getCate($cateAll, $v['id']);
            }
        }
        return $cate;
    }
    public function uploadImg($img)
    {
        // 获取表单上传文件
        try {
            $files = input("file." . $img);
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
            exit;
        }
        if (!$files) return [false, '没上传图'];
        //判断单图多图
        if (is_array($files)) {
            try {
                validate(['image' => 'fileSize:1048576|fileExt:jpg,png'])
                    ->check(['image' => $files]);
            } catch (ValidateException $e) {
                return [false, $e->getMessage()];
                exit;
            }
            $path = [];
            foreach ($files as $file) {
                $img = \think\facade\Filesystem::putFile('UploadFiles\product', $file);
                $path[] = str_replace('\\', '/', $img);
            }
            $path = implode(',', $path);
        } else {
            try {
                validate(['image' => 'fileSize:1048576|fileExt:jpg,png'])
                    ->check(['image' => $files]);
            } catch (ValidateException $e) {
                return [false, $e->getMessage()];
                exit;
            }
            $img = \think\facade\Filesystem::putFile('UploadFiles\product', $files);
            $path = str_replace('\\', '/', $img);
        }
        return [true, $path];
        exit;
    }
    public function file()
    {
        try {
            $files = input('file.img');
        } catch (\Exception $e) {
            echo json_encode([false, '没上传图']);
            exit;
        }
        if (!$files) echo json_encode([false, '没上传图']);
        //判断单图多图
        if (is_array($files)) {
            try {
                validate(['image' => 'fileSize:1048576|fileExt:jpg,png'])
                    ->check(['image' => $files]);
            } catch (ValidateException $e) {
                echo json_encode([false, $e->getMessage()]);
                exit;
            }
            $path = [];
            foreach ($files as $file) {
                $img = \think\facade\Filesystem::putFile('UploadFiles\product', $file);
                $path[] = str_replace('\\', '/', $img);
            }
            $path = implode(',', $path);
        } else {
            try {
                validate(['image' => 'fileSize:1048576|fileExt:jpg,png'])
                    ->check(['image' => $files]);
            } catch (ValidateException $e) {
                echo json_encode([false, $e->getMessage()]);
                exit;
            }
            $img = \think\facade\Filesystem::putFile('UploadFiles\product', $files);
            $path = str_replace('\\', '/', $img);
        }
        echo json_encode([true, $path]);
        exit;
    }
}
